<?php

namespace App\Jobs;

use App\Services\SplitService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class AutomaticSplitJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(): void
    {
        DB::beginTransaction();
        try {
            $result = SplitService::splitHandle($this->data);
            DB::commit();
            echo json_encode($result, JSON_UNESCAPED_UNICODE);
        } catch (\Exception $e) {
            DB::rollBack();
            echo json_encode(['code' => 2, "msg" => $e->getMessage()], JSON_UNESCAPED_UNICODE);
        }

        //如果任务执行成功后 记得删除任务，不然这个任务会重复执行，直到达到最大重试次数后失败后，执行failed方法
    }

    public function failed(): void
    {
        self::dispatch($this->data)->onQueue('AutomaticSplitJob')->delay(now()->addMinutes(1.5)->timestamp);
    }
}
